<template>
	<view class="search-container">
		<!-- 搜索头部 -->
		<view class="search-header">
			<view class="search-input-wrapper">
				<view class="search-input-box">
					<text class="search-icon">🔍</text>
					<input
						class="search-input"
						type="text"
						v-model="searchKeyword"
						placeholder="搜索停车场名称或地址"
						:focus="true"
						@input="handleSearchInput"
						@confirm="handleSearch"
						confirm-type="search"
					/>
					<text
						v-if="searchKeyword"
						class="clear-icon"
						@click="clearSearch"
					>✕</text>
				</view>
			</view>
			<text class="cancel-btn" @click="goBack">取消</text>
		</view>

		<!-- 搜索内容区域 -->
		<view class="search-content">
			<!-- 搜索建议（输入时显示） -->
			<view v-if="showSuggestions && suggestions.length > 0" class="suggestions-section">
				<view class="section-title">搜索建议</view>
				<view class="suggestions-list">
					<view
						v-for="(suggestion, index) in suggestions"
						:key="index"
						class="suggestion-item"
						@click="selectSuggestion(suggestion)"
					>
						<text class="suggestion-icon">🔍</text>
						<text class="suggestion-text">{{ suggestion }}</text>
					</view>
				</view>
			</view>

			<!-- 搜索加载状态 -->
			<view v-if="loading && currentPage === 1" class="loading-section">
				<view class="loading-content">
					<text class="loading-icon">🔍</text>
					<text class="loading-text">正在搜索...</text>
				</view>
			</view>

			<!-- 搜索结果 -->
			<view v-if="showResults" class="results-section">
				<view class="results-header">
					<text class="results-count">找到 {{ totalResults }} 个停车场</text>
				</view>

				<!-- 结果列表 -->
				<view class="results-list">
					<view
						v-for="(parking, index) in searchResults"
						:key="parking.id"
						class="result-item"
						@click="handleParkingClick(parking)"
					>
						<image
							class="result-image"
							:src="getParkingImage(parking)"
							mode="aspectFill"
							@error="handleImageError"
						></image>
						<view class="result-info">
							<text class="result-name">{{ parking.name }}</text>
							<text class="result-address">{{ parking.address }}</text>
							

							
							<!-- 价格信息 -->
							<view class="result-price">
								<view class="price-container">
									<text class="price-text">{{ getPriceDisplay(parking) }}</text>
									<text class="price-note" v-if="hasMultiplePrices(parking)">
										{{ getPriceRangeNote(parking) }}
									</text>
								</view>
								<text v-if="parking.available_spaces > 0" class="available-spaces">
									剩余{{ parking.available_spaces }}个车位
								</text>
							</view>

							<!-- 服务设施标签 -->
							<view class="facilities-tags" v-if="getFacilitiesTags(parking).length > 0">
								<text
									class="facility-tag"
									v-for="(tag, tagIndex) in getFacilitiesTags(parking)"
									:key="tagIndex"
								>
									{{ tag }}
								</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 加载更多 -->
				<view v-if="hasMore" class="load-more" @click="loadMore">
					<text class="load-more-text">{{ loading ? '加载中...' : '加载更多' }}</text>
				</view>

				<!-- 没有更多数据 -->
				<view v-if="!hasMore && searchResults.length > 0" class="no-more">
					<text class="no-more-text">没有更多数据了</text>
				</view>
			</view>

			<!-- 空搜索结果 -->
			<view v-if="showEmptyResult" class="empty-result">
				<text class="empty-icon">🔍</text>
				<text class="empty-title">未找到相关停车场</text>
				<text class="empty-desc">试试其他关键词或检查拼写</text>
			</view>

			<!-- 默认状态（搜索历史和热门搜索） -->
			<view v-if="showDefaultContent" class="default-content">
				<!-- 搜索历史 -->
				<view v-if="searchHistory.length > 0" class="history-section">
					<view class="section-header">
						<text class="section-title">搜索历史</text>
						<text class="clear-history" @click="clearHistory">清空</text>
					</view>
					<view class="history-list">
						<view
							v-for="(item, index) in searchHistory"
							:key="index"
							class="history-item"
							@click="selectHistory(item)"
						>
							<text class="history-icon">🕐</text>
							<text class="history-text">{{ item }}</text>
							<text class="remove-history" @click.stop="removeHistory(index)">✕</text>
						</view>
					</view>
				</view>

				<!-- 热门搜索 -->
				<view class="hot-search-section">
					<view class="section-title">热门搜索</view>
					<view class="hot-search-list">
						<text
							v-for="(item, index) in hotSearchList"
							:key="index"
							class="hot-search-item"
							@click="selectHotSearch(item)"
						>
							{{ item }}
						</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { searchParkingLots } from '../../api/parking.js'
import { getFullImageUrl } from '../../utils/request.js'

// 响应式数据
const searchKeyword = ref('')
const searchResults = ref([])
const loading = ref(false)
const currentPage = ref(1)
const totalResults = ref(0)
const hasMore = ref(false)
const searchHistory = ref([])
const suggestions = ref([])

// 热门搜索数据
const hotSearchList = ref([
	'万达广场', '市中心', '医院停车场', '学校附近', '商场停车',
	'地铁站停车', '火车站', '机场停车场', '体育馆', '公园停车',
	'24小时停车', '充电桩停车', '室内停车场', '免费停车'
])

// 计算属性
const showSuggestions = computed(() => {
	return searchKeyword.value.length > 0 && !showResults.value && suggestions.value.length > 0
})

const showResults = computed(() => {
	return searchResults.value.length > 0
})

const showEmptyResult = computed(() => {
	return searchKeyword.value.length > 0 && searchResults.value.length === 0 && !loading.value
})

const showDefaultContent = computed(() => {
	return searchKeyword.value.length === 0
})

// 页面方法
const goBack = () => {
	uni.navigateBack()
}

const clearSearch = () => {
	searchKeyword.value = ''
	searchResults.value = []
	suggestions.value = []
	currentPage.value = 1
	totalResults.value = 0
	hasMore.value = false
}

// 防抖定时器
let debounceTimer: any = null

// 搜索输入处理
const handleSearchInput = (e: any) => {
	const value = e.detail.value
	searchKeyword.value = value

	// 清除之前的定时器
	if (debounceTimer) {
		clearTimeout(debounceTimer)
	}

	if (value.length > 0) {
		// 防抖处理，500ms后生成建议
		debounceTimer = setTimeout(() => {
			generateSuggestions(value)
		}, 500)
	} else {
		suggestions.value = []
	}
}

// 生成搜索建议
const generateSuggestions = (keyword: string) => {
	const trimmedKeyword = keyword.trim()
	if (!trimmedKeyword) {
		suggestions.value = []
		return
	}

	// 从搜索历史中匹配相关建议
	const historySuggestions = searchHistory.value.filter((item: string) =>
		item.toLowerCase().includes(trimmedKeyword.toLowerCase())
	).slice(0, 2)

	// 生成通用建议
	const commonSuggestions = [
		`${trimmedKeyword}停车场`,
		`${trimmedKeyword}商场停车`,
		`${trimmedKeyword}停车位`
	]

	// 合并建议，去重并限制数量
	const allSuggestions = [...historySuggestions, ...commonSuggestions]
	const uniqueSuggestions = [...new Set(allSuggestions)]
	suggestions.value = uniqueSuggestions.slice(0, 4)
}

// 选择搜索建议
const selectSuggestion = (suggestion: string) => {
	searchKeyword.value = suggestion
	handleSearch()
}

// 执行搜索
const handleSearch = async () => {
	if (!searchKeyword.value.trim()) {
		return
	}

	// 添加到搜索历史
	addToHistory(searchKeyword.value.trim())
	
	// 重置搜索状态
	currentPage.value = 1
	searchResults.value = []
	suggestions.value = []
	
	await performSearch()
}

// 执行搜索请求
const performSearch = async () => {
	if (loading.value) return

	loading.value = true
	try {
		const params = {
			keyword: searchKeyword.value.trim(),
			page: currentPage.value,
			limit: 10
		}

		const response = await searchParkingLots(params)

		if (response.success) {
			const newResults = response.data.list || []

			if (currentPage.value === 1) {
				searchResults.value = newResults
			} else {
				searchResults.value = [...searchResults.value, ...newResults]
			}

			totalResults.value = response.data.total || 0
			hasMore.value = searchResults.value.length < totalResults.value
		} else {
			// 处理API返回的错误
			uni.showToast({
				title: response.message || '搜索失败',
				icon: 'none',
				duration: 2000
			})
		}
	} catch (error) {
		console.error('搜索失败:', error)

		// 根据错误类型显示不同提示
		let errorMessage = '搜索失败，请重试'
		if (error.message && error.message.includes('timeout')) {
			errorMessage = '请求超时，请检查网络连接'
		} else if (error.message && error.message.includes('network')) {
			errorMessage = '网络连接失败，请检查网络设置'
		}

		uni.showToast({
			title: errorMessage,
			icon: 'none',
			duration: 2000
		})
	} finally {
		loading.value = false
	}
}

// 加载更多
const loadMore = async () => {
	if (!hasMore.value || loading.value) return
	
	currentPage.value++
	await performSearch()
}

// 搜索历史管理
const addToHistory = (keyword: string) => {
	const trimmedKeyword = keyword.trim()
	if (!trimmedKeyword || trimmedKeyword.length < 2) {
		return // 不保存太短的搜索词
	}

	const history = [...searchHistory.value]
	const index = history.indexOf(trimmedKeyword)

	if (index > -1) {
		history.splice(index, 1)
	}

	history.unshift(trimmedKeyword)
	searchHistory.value = history.slice(0, 10) // 最多保存10条

	// 保存到本地存储
	try {
		uni.setStorageSync('search_history', searchHistory.value)
	} catch (error) {
		console.error('保存搜索历史失败:', error)
	}
}

const selectHistory = (keyword: string) => {
	searchKeyword.value = keyword
	handleSearch()
}

const removeHistory = (index: number) => {
	searchHistory.value.splice(index, 1)
	uni.setStorageSync('search_history', searchHistory.value)
}

const clearHistory = () => {
	uni.showModal({
		title: '确认清空',
		content: '确定要清空所有搜索历史吗？',
		success: (res: any) => {
			if (res.confirm) {
				searchHistory.value = []
				try {
					uni.removeStorageSync('search_history')
					uni.showToast({
						title: '已清空搜索历史',
						icon: 'success',
						duration: 1500
					})
				} catch (error) {
					console.error('清空搜索历史失败:', error)
				}
			}
		}
	})
}

// 选择热门搜索
const selectHotSearch = (keyword: string) => {
	searchKeyword.value = keyword
	handleSearch()
}

// 停车场点击处理
const handleParkingClick = (parking: any) => {
	uni.navigateTo({
		url: `/pages/detail/detail?id=${parking.id}`
	})
}

// 获取停车场图片
const getParkingImage = (parking: any) => {
	if (parking.images && parking.images.length > 0) {
		return getFullImageUrl(parking.images[0])
	}
	return '/static/parking-default.svg'
}

// 图片加载错误处理
const handleImageError = (e: any) => {
	e.target.src = '/static/parking-default.svg'
}



// 获取价格显示
const getPriceDisplay = (parking: any) => {
	// 如果有价格规则，显示价格范围
	if (parking.price_rules && Array.isArray(parking.price_rules) && parking.price_rules.length > 0) {
		const prices = parking.price_rules.map((rule: any) => Number(rule.price_per_hour) || 0)
		const minPrice = Math.min(...prices)
		const maxPrice = Math.max(...prices)

		if (minPrice === maxPrice) {
			return `¥${minPrice}/小时`
		} else {
			// 显示最低价格，突出优惠
			return `¥${minPrice}起/小时`
		}
	}

	// 兼容旧的 hourly_rate 字段
	if (parking.hourly_rate) {
		return `¥${parking.hourly_rate}/小时`
	}

	// 兼容旧的 price 字段
	if (parking.price) {
		return `¥${parking.price}/小时`
	}

	return '价格面议'
}

// 检查是否有多个价格
const hasMultiplePrices = (parking: any) => {
	if (parking.price_rules && Array.isArray(parking.price_rules) && parking.price_rules.length > 1) {
		const prices = parking.price_rules.map((rule: any) => Number(rule.price_per_hour) || 0)
		const minPrice = Math.min(...prices)
		const maxPrice = Math.max(...prices)
		return minPrice !== maxPrice
	}
	return false
}

// 获取价格范围提示
const getPriceRangeNote = (parking: any) => {
	if (parking.price_rules && Array.isArray(parking.price_rules) && parking.price_rules.length > 0) {
		const prices = parking.price_rules.map((rule: any) => Number(rule.price_per_hour) || 0)
		const minPrice = Math.min(...prices)
		const maxPrice = Math.max(...prices)

		if (minPrice !== maxPrice) {
			return `¥${minPrice}-${maxPrice}/时`
		} else {
			return '统一计费'
		}
	}
	return '多时段计费'
}

// 获取服务设施标签
const getFacilitiesTags = (parking: any) => {
	const tags: string[] = []

	if (parking.service_facilities && Array.isArray(parking.service_facilities)) {
		const facilityMap: Record<string, string> = {
			'has_charging_pile': '充电桩',
			'is_24_hours': '24小时',
			'has_camera': '监控',
			'is_indoor': '室内',
			'has_24h_shuttle': '24H接送',
			'has_staff_on_duty': '专人值守',
			'has_surveillance': '监控',
			'has_7_seat_shuttle': '7座接送',
			'has_5_seat_shuttle': '5座接送',
			'has_parking_invoice': '发票',
			'walking_distance': '步行即达'
		}

		parking.service_facilities.forEach((facility: string) => {
			if (facilityMap[facility]) {
				tags.push(facilityMap[facility])
			}
		})
	}

	return tags.slice(0, 3)
}

// 生命周期
onMounted(() => {
	// 加载搜索历史
	try {
		const history = uni.getStorageSync('search_history')
		if (history && Array.isArray(history)) {
			searchHistory.value = history
		}
	} catch (error) {
		console.error('加载搜索历史失败:', error)
	}
})
</script>

<style scoped>
.search-container {
	background-color: #f5f5f5;
	min-height: 100vh;
}

/* 搜索头部样式 */
.search-header {
	background: white;
	padding: 20rpx;
	display: flex;
	align-items: center;
	border-bottom: 1rpx solid #f0f0f0;
}

.search-input-wrapper {
	flex: 1;
	margin-right: 20rpx;
}

.search-input-box {
	background: #f5f5f5;
	border-radius: 50rpx;
	padding: 20rpx 30rpx;
	display: flex;
	align-items: center;
}

.search-icon {
	font-size: 32rpx;
	color: #999;
	margin-right: 20rpx;
}

.search-input {
	flex: 1;
	font-size: 28rpx;
	color: #333;
	background: transparent;
	border: none;
	outline: none;
}

.clear-icon {
	font-size: 28rpx;
	color: #999;
	padding: 10rpx;
}

.cancel-btn {
	font-size: 28rpx;
	color: #007AFF;
}

/* 搜索内容区域 */
.search-content {
	padding: 20rpx;
}

/* 加载状态样式 */
.loading-section {
	background: white;
	border-radius: 20rpx;
	padding: 60rpx 20rpx;
	margin-bottom: 20rpx;
	text-align: center;
}

.loading-content {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.loading-icon {
	font-size: 60rpx;
	color: #007AFF;
	margin-bottom: 20rpx;
	animation: rotate 2s linear infinite;
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}

@keyframes rotate {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}

/* 搜索建议样式 */
.suggestions-section {
	background: white;
	border-radius: 20rpx;
	padding: 30rpx 20rpx;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 28rpx;
	color: #333;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.suggestions-list {
	/* 建议列表样式 */
}

.suggestion-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.suggestion-item:last-child {
	border-bottom: none;
}

.suggestion-icon {
	font-size: 28rpx;
	color: #999;
	margin-right: 20rpx;
}

.suggestion-text {
	font-size: 28rpx;
	color: #333;
}

/* 搜索结果样式 */
.results-section {
	/* 结果区域样式 */
}

.results-header {
	margin-bottom: 20rpx;
}

.results-count {
	font-size: 26rpx;
	color: #666;
}

.results-list {
	/* 结果列表样式 */
}

.result-item {
	background: white;
	border-radius: 20rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	display: flex;
}

.result-image {
	width: 160rpx;
	height: 120rpx;
	border-radius: 10rpx;
	margin-right: 20rpx;
	flex-shrink: 0;
}

.result-info {
	flex: 1;
	display: flex;
	flex-direction: column;
}

.result-name {
	font-size: 30rpx;
	color: #333;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.result-address {
	font-size: 26rpx;
	color: #666;
	margin-bottom: 10rpx;
}

.result-distance {
	font-size: 24rpx;
	color: #007AFF;
	margin-bottom: 10rpx;
}

.result-price {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 10rpx;
}

.price-container {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.price-text {
	font-size: 28rpx;
	color: #ff6b35;
	font-weight: bold;
	background: rgba(255, 107, 53, 0.1);
	padding: 6rpx 12rpx;
	border-radius: 12rpx;
	border: 1rpx solid rgba(255, 107, 53, 0.2);
}

.price-note {
	font-size: 20rpx;
	color: #007AFF;
	background: rgba(0, 122, 255, 0.1);
	padding: 2rpx 8rpx;
	border-radius: 8rpx;
	border: 1rpx solid rgba(0, 122, 255, 0.2);
}

.available-spaces {
	font-size: 24rpx;
	color: #28a745;
}

.facilities-tags {
	display: flex;
	flex-wrap: wrap;
	gap: 10rpx;
}

.facility-tag {
	background: #f0f8ff;
	color: #007AFF;
	font-size: 22rpx;
	padding: 6rpx 12rpx;
	border-radius: 20rpx;
}

/* 加载更多样式 */
.load-more {
	text-align: center;
	padding: 30rpx;
	background: white;
	border-radius: 20rpx;
	margin-top: 20rpx;
}

.load-more-text {
	font-size: 28rpx;
	color: #007AFF;
}

.no-more {
	text-align: center;
	padding: 30rpx;
}

.no-more-text {
	font-size: 26rpx;
	color: #999;
}

/* 空结果样式 */
.empty-result {
	text-align: center;
	padding: 100rpx 20rpx;
	background: white;
	border-radius: 20rpx;
}

.empty-icon {
	font-size: 100rpx;
	color: #ddd;
	display: block;
	margin-bottom: 30rpx;
}

.empty-title {
	font-size: 32rpx;
	color: #333;
	display: block;
	margin-bottom: 20rpx;
}

.empty-desc {
	font-size: 26rpx;
	color: #999;
	display: block;
}

/* 默认内容样式 */
.default-content {
	/* 默认内容区域 */
}

/* 搜索历史样式 */
.history-section {
	background: white;
	border-radius: 20rpx;
	padding: 30rpx 20rpx;
	margin-bottom: 20rpx;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.clear-history {
	font-size: 26rpx;
	color: #999;
}

.history-list {
	/* 历史列表样式 */
}

.history-item {
	display: flex;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.history-item:last-child {
	border-bottom: none;
}

.history-icon {
	font-size: 28rpx;
	color: #999;
	margin-right: 20rpx;
}

.history-text {
	flex: 1;
	font-size: 28rpx;
	color: #333;
}

.remove-history {
	font-size: 24rpx;
	color: #999;
	padding: 10rpx;
}

/* 热门搜索样式 */
.hot-search-section {
	background: white;
	border-radius: 20rpx;
	padding: 30rpx 20rpx;
}

.hot-search-list {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.hot-search-item {
	background: #f5f5f5;
	color: #333;
	font-size: 26rpx;
	padding: 16rpx 24rpx;
	border-radius: 30rpx;
}
</style>
